<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="板块id" prop="sid">
        <!-- <el-input
          v-model="queryParams.sid"
          placeholder="请输入板块id"
          clearable
          @keyup.enter="handleQuery"
        /> -->
      </el-form-item>
      <el-form-item label="社区名称" prop="communityName">
        <el-input
          v-model="queryParams.communityName"
          placeholder="请输入社区名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="添加时间" prop="addTime">
        <el-date-picker
          clearable
          v-model="queryParams.addTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择添加时间"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="收藏人数" prop="collectNumber">
        <el-input
          v-model="queryParams.collectNumber"
          placeholder="请输入收藏人数"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="群聊二维码" prop="qrCode">
        <el-input
          v-model="queryParams.qrCode"
          placeholder="请输入群聊二维码"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['ds:community:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['ds:community:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['ds:community:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['ds:community:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="communityList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" />
      <!-- <el-table-column label="板块id" align="center" prop="sid" /> -->
      <el-table-column label="社区名称" align="center" prop="communityName" />
      <el-table-column
        label="社区图片"
        align="center"
        prop="communityImage"
        width="100"
      >
        <template #default="scope">
          <image-preview
            :src="scope.row.communityImage"
            :width="50"
            :height="50"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="添加时间"
        align="center"
        prop="addTime"
        width="180"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.addTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" >
        <template #default="scope">
          <span v-if="scope.row.status == 1">启用</span>
          <span v-else>删除</span>
        </template>
      </el-table-column>
      <el-table-column label="收藏人数" align="center" prop="collectNumber" />
      <el-table-column label="群聊二维码" align="center" prop="qrCode">
        <template #default="scope">
          <image-preview :src="scope.row.qrCode" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['ds:community:edit']"
            >修改</el-button
          >
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['ds:community:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改社区信息对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form
        ref="communityRef"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="社区名称" prop="communityName">
          <el-input v-model="form.communityName" placeholder="请输入社区名称" />
        </el-form-item>
        <el-form-item label="社区图片" prop="communityImage">
          <image-upload v-model="form.communityImage" />
        </el-form-item>
        <el-form-item label="添加时间" prop="addTime">
          <el-date-picker
            clearable
            v-model="form.addTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择添加时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="收藏人数" prop="collectNumber">
          <el-input v-model="form.collectNumber" placeholder="请输入收藏人数" />
        </el-form-item>
        <el-form-item label="群聊二维码" prop="qrCode">
          <image-upload v-model="form.qrCode" />
        </el-form-item>

        <el-form-item label="地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入地址" @blur="handleGetLocation" />
          <span v-if="form.longitude">{{ form.longitude }},{{ form.dimension }}</span>
        </el-form-item>

        <el-form-item label="位置地图" v-if="form.longitude && form.dimension">
          <div id="map-container" style="width: 100%; height: 300px;"></div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Community">
import {
  listCommunity,
  getCommunity,
  delCommunity,
  addCommunity,
  updateCommunity,
} from "@/api/ds/community";

import axios from "axios"

import AMapLoader from '@amap/amap-jsapi-loader';

const map = ref(null)
const { proxy } = getCurrentInstance();

const communityList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    sid: null,
    communityName: null,
    communityImage: null,
    addTime: null,
    status: null,
    collectNumber: null,
    qrCode: null,
  },
  rules: {},
});

const { queryParams, form, rules } = toRefs(data);

/** 查询社区信息列表 */
function getList() {
  loading.value = true;
  listCommunity(queryParams.value).then((response) => {
    communityList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    sid: null,
    communityName: null,
    communityImage: null,
    addTime: null,
    status: null,
    collectNumber: null,
    qrCode: null,
  };
  proxy.resetForm("communityRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

const initMap = () => {
  AMapLoader.load({
    key: 'fbacb26edf56429309b33c7ed0e37d0b', // 您的高德地图key
    version: '2.0',
    plugins: ['AMap.Marker']
  }).then((AMap) => {
    map.value = new AMap.Map('map-container', {
      zoom: 15,  // 缩放级别
      center: [form.value.longitude, form.value.dimension]  // 中心点坐标
    });

    // 添加标准图层
    const tileLayer = new AMap.TileLayer({
      zIndex: 10
    });
    map.value.add(tileLayer);

    // 添加标记点
    new AMap.Marker({
      position: new AMap.LngLat(form.value.longitude, form.value.dimension),
      map: map.value
    });
  }).catch(e => {
    console.error(e);
  });
};

const handleGetLocation = async () => {


  // 获取经纬度
  const key = 'fbacb26edf56429309b33c7ed0e37d0b'

  // 判断地址
  let resp = await axios({
    url: `https://restapi.amap.com/v3/geocode/geo?key=${key}&address=${form.value.address}`,
    method: 'GET',
  })


  if (resp.data.status == 1) {
    let location = resp.data.geocodes[0].location
    form.value.longitude = location.split(',')[0]
    form.value.dimension = location.split(',')[1]

    // 初始化地图
    nextTick(() => {
      initMap();
    });
  } else {
    proxy.$modal.msgSuccess("定位获取失败")
    return
  }

}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加社区信息";

  nextTick(() => {
      initMap();
    });
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value;
  getCommunity(_id).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改社区信息";

    nextTick(() => {
      initMap();
    });
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["communityRef"].validate((valid) => {
    if (valid) {
      if (form.value.id != null) {
        updateCommunity(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addCommunity(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除社区信息编号为"' + _ids + '"的数据项？')
    .then(function () {
      return delCommunity(_ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "ds/community/export",
    {
      ...queryParams.value,
    },
    `community_${new Date().getTime()}.xlsx`
  );
}

getList();
</script>
